package servidores;

import java.awt.Color;
import java.awt.GridLayout;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import paquete_aux.Comun;

public class ServidorEntidadCertificadora extends JFrame {

	private static final long serialVersionUID = 1L;

	private ServerSocket providerSocket;
	private Socket connection;
	private PrintWriter out;
	private BufferedReader in;

	private int veces;

	public static void main(String[] args) {
		new ServidorEntidadCertificadora();
	}

	public ServidorEntidadCertificadora() {
		veces = 1;
		try {
			UIManager.setLookAndFeel(UIManager
					.getCrossPlatformLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		setVisible(true);
		setSize(290, 65);
		setLocationRelativeTo(null);
		setTitle("Servidor de Entidad cerificadora");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setBackground(Color.BLACK);
		setLayout(new GridLayout());
		JLabel hola = new JLabel("........");
		hola.setBackground(Color.BLACK);
		add(hola);
		cargarServidor();
	}

	public void cargarServidor() {
		System.out.println("----------------------------------------\nOn: "
				+ veces);
		try {

			providerSocket = new ServerSocket(Comun.PUERTO_EC);
			System.out.println("---1<Waiting for connection");
			connection = providerSocket.accept();
			System.out.println("---2<" + connection.getLocalAddress().getHostAddress());



			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			System.out.println("asd");
			String respuesta = in.readLine();

			System.out.println(respuesta);

			out = new PrintWriter(connection.getOutputStream());
			out.flush();



			if (respuesta.equals("HELLO")) {

				out.write("RECEIVED:OK:" + Comun.LLAVE_PUBLICA_SERVIDOR
						+ ":" + Comun.LLAVE_PRIVADA_CLIENTE + ":"
						+ Comun.LLAVE_PUBLICA_CLIENTE);
				out.flush();
			} else {
				out.write("RECEIVED:DENIED");
			}
			out.close();
			connection.close();
			providerSocket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		veces++;
		//cargarServidor();
	}
}